/*
  LinPVR - Linux Personal Video Recorder
  Copyright (C) 2006 Kamil Pawlowski <kamilpe@gmail.com>

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.
  
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
#include "audio.h"
#include "debug.h"

int audiodev_open(audiodev_t *device, const char *handle, int channels, int rate, int mode)
{
  snd_pcm_hw_params_t *hw_params;

  DEBUG_ENTER("audiodev_open");
  
  if (snd_pcm_open(&device->device, handle, mode, 0) < 0)
    return ERR_AUDIO;

  if (snd_pcm_hw_params_malloc(&hw_params) < 0)
    return ERR_MALLOC;

  if (snd_pcm_hw_params_any(device->device, hw_params) < 0 ||
      snd_pcm_hw_params_set_access(device->device, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED) < 0 ||
      snd_pcm_hw_params_set_format(device->device, hw_params, SND_PCM_FORMAT_S16_LE) < 0 ||
      snd_pcm_hw_params_set_rate_near(device->device, hw_params, &rate, 0) < 0 ||
      snd_pcm_hw_params_set_channels(device->device, hw_params, 2) < 0 ||
      snd_pcm_hw_params_set_periods(device->device, hw_params, channels, 0) < 0 ||
      snd_pcm_hw_params_set_buffer_size(device->device, hw_params, AUDIO_SAMPLES * 4 * channels) < 0 ||
      snd_pcm_hw_params(device->device, hw_params) < 0)
    return ERR_AUDIO;
  
  snd_pcm_hw_params_free(hw_params);

  if (snd_pcm_prepare(device->device) < 0)
    return ERR_AUDIO;
}

void audiodev_close(audiodev_t *device)
{
  DEBUG_ENTER("audiodev_close");
  snd_pcm_close(device->device);
}

